package org.example.mppg.handler;

import cn.hutool.core.util.ObjectUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.postgis.Geometry;
import org.postgis.PGgeometry;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;

/**
 * 共用一个Geometry类型（上面的类型具体一点，这个包含以上几种类型）
 *
 * @Description GeometryTypeHandler
 * @Author guoyb
 * @Date 2025/7/14 22:18
 */
@MappedJdbcTypes(JdbcType.OTHER)
public class GeometryTypeHandler extends BaseTypeHandler<Object> {
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        //将wkt类型字符串转换为postgis类型PGgeometry用来实现自动入库
        //注意 wkt的类型必须为大写 类如（point 必须为：POINT）
        if (ObjectUtil.isNotNull(parameter)) {
            String wkt = parameter.toString();
            PGgeometry pGgeometry = new PGgeometry(wkt);
            pGgeometry.getGeometry().setSrid(4528);
            ps.setObject(i, pGgeometry);
        }

    }

    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object object = Optional.ofNullable(rs.getObject(columnName)).orElseGet(Object::new);
        if (object instanceof PGgeometry) {
            Geometry geometry = ((PGgeometry) object).getGeometry();
            return geometry.getTypeString() + geometry.getValue();
        }
        return object;
    }

    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        PGgeometry pGgeometry = (PGgeometry) rs.getObject(columnIndex);
        if (pGgeometry == null) {
            return null;
        }
        return pGgeometry.getGeometry();
    }

    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        PGgeometry pGgeometry = (PGgeometry) cs.getObject(columnIndex);
        if (pGgeometry == null) {
            return null;
        }
        return pGgeometry.getGeometry();
    }
}